﻿using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Redis_Factory
{
    public class GetRedisClient
    {
        public static RedisClient Get()
        {
            try
            {
                string url = ConfigurationManager.AppSettings["ConnectionIP"];
                string port = ConfigurationManager.AppSettings["ConnectionPort"];
                if(string.IsNullOrEmpty(url) || string.IsNullOrEmpty(port))
                {
                    throw new Exception("连接IP或端口号为空");
                }
                if (!IsNetReachable(url))
                    throw new Exception("连接异常");

                return new RedisClient(url, Convert.ToInt32(port));
            }
            catch (Exception)
            {

                throw;
            }
        }


        /// <summary>
        /// 通过Ping在NetConnect前检查网络是否可达
        /// </summary>
        /// <returns></returns>
        public static bool IsNetReachable(string destIp)
        {
            try
            {
                Ping p = new Ping();
                string serverIP = destIp;
                PingReply pr = p.Send(serverIP, 1000);
                Thread.Sleep(1500);

                if (pr.Status == IPStatus.Success)
                    return true;
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }


    }
}
